/**
 * @description: flatArray
 * @author: huen2015
 */

import { IFn } from './types'

// level < 0 => 深层扁平化
function flatArray1(arr: any[], level = 0): any[] {
	let result: any[] = []

	arr.forEach((item: any) => {
		if (level !== 0 && Array.isArray(item)) {
			// 扁平 1 层
			result = result.concat(flatArray(item, level - 1))
		} else {
			result = result.concat([item])
		}
	})

	return result
}

// @ts-ignore
Array.prototype.reduce1 = function (reducer: IFn, init: any): any {
	const arr: any[] = this
	let pre: any = init ? init : arr[0]

	arr.forEach((item: any, index: number) => {
		if (init || (!init && index > 0)) {
			pre = reducer(pre, item)
		}
	})

	return pre
}

// level < 0 => 深层扁平化
function flatArray(arr: any[], level = 0): any[] {
	if (level !== 0) {
		// @ts-ignore
		return arr.reduce1((pre: any, cur: any) => {
			return pre.concat(
				Array.isArray(cur) ? flatArray(cur, level - 1) : cur,
			)
		}, [])
	}
	return arr.slice()
}

const flatArrayData = [1, 2, 3, [[4, 5], 6], 7, 8]
const flatArrayResult0 = flatArray1(flatArrayData, 0)
const flatArrayResult1 = flatArray1(flatArrayData, 1)
const flatArrayResult2 = flatArray1(flatArrayData, 2)
const flatArrayResult3 = flatArray1(flatArrayData)
const flatArrayResult4 = flatArray1(flatArrayData, -100)
console.log('flatArrayResult0', flatArrayResult0) // [1, 2, 3, [[4, 5], 6], 7, 8]
console.log('flatArrayResult1', flatArrayResult1) // [1, 2, 3, [[4, 5], 6, 7, 8]
console.log('flatArrayResult2', flatArrayResult2) // [1, 2, 3, 4, 5, 6, 7, 8]
console.log('flatArrayResult3', flatArrayResult3) // [1, 2, 3, [[4, 5], 6], 7, 8]
console.log('flatArrayResult4', flatArrayResult4) // [1, 2, 3, 4, 5, 6, 7, 8]

export { flatArray }
